﻿using Microsoft.EntityFrameworkCore;
using TuLing.Blazor.Dto;
using TulingMember.Core;

namespace TuLing.Blazor.Services
{
    public class CustomerService: BaseService
    {
        public CustomerService(DefaultDbContext context) : base(context) { }

        public List<Customer> SearchCustomer(BaseInput input)
        {
            if(string.IsNullOrEmpty(input.keyword))
                return _context.Customers.AsNoTracking().ToList();
            return _context.Customers.AsNoTracking().Where(m =>
                m.Name.Contains(input.keyword, StringComparison.OrdinalIgnoreCase) ||
                m.Phone.Contains(input.keyword, StringComparison.OrdinalIgnoreCase)).ToList();
        }

        public void SaveCustomer(Customer input)
        {
            var has = _context.Customers.Any(m => m.Name.Equals(input.Name) && m.Id!=input.Id);
            if (has)
            {
                throw new Exception("客户名称已存在，请检查");
            }

            // 更新客户信息
            if (input.Id > 0)
            {
                _context.Customers.Update(input);
                _context.SaveChanges();
            }
            else {

                // 新增客户
                _context.Customers.Add(input);
                _context.SaveChanges();
            }             
        }

        /// <summary>
        /// 获取
        /// </summary>  
        public Customer? GetCustomer(long id)
        {
           var custom = _context.Customers.FirstOrDefault(s=>s.Id == id);
           return custom;
        }

        /// <summary>
        /// 删除 
        /// </summary>  
        public void DeleteCustomer(Customer customer)
        {
            _context.Customers.Remove(customer);
            _context.SaveChanges();
        }

        /// <summary>
        /// 客户账目明细
        /// </summary> 
        public IEnumerable<CustomerPayLog> SearchCustomerPayLog(BaseInput input)
        {
            return _context.CustomerLogs.Where(m => m.CustomerId == input.customerid);            
        }

        /// <summary>
        /// 新增一条账目明细
        /// </summary> 
        public void AddCustomerPayLog(CustomerPayLog input)
        {
            var customer = _context.Customers.FirstOrDefault(s=> s.Id == input.CustomerId);
            _context.CustomerLogs.Add(input);
            _context.SaveChanges();
        }

    }
}
